/**
 iTextUploader
 (C) 2008 MyselftDev (myselftdev@gmail.com)
 
 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; version 2
 of the License.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

/* Revision: $Id: PreferencesView.m 59 2009-01-29 20:25:29Z myselftdev $ */

#import "PreferencesView.h"

@implementation PreferencesView

- (id)initWithFrame:(CGRect)frame
	dataObject:(PreferencesData*)theDataObject
	homeViewObject:(HomeView*)theHomeViewObject
	mainViewObject:(MainView*)theMainViewObject
{
	if ((self = [super initWithFrame:frame]))
	{
		data = [theDataObject retain];
		home = [theHomeViewObject retain];
		mainView = [theMainViewObject retain];
		
		mainView.navItem.title = @"Preferences";
		
		self.backgroundColor = [UIColor colorWithWhite:1.0 alpha:1.0];
		
		BOOL disableSwitch = NO;
		CGRect boxFrame = CGRectMake(15.0, 0.0, 280.0, 0.0);
		
		// Label for username field
		boxFrame.origin.y = boxFrame.origin.y + 15.0;
		boxFrame.size.height = 22.0;
		usernameLabel = [ [UILabel alloc] initWithFrame:boxFrame];
		usernameLabel.text = @"Username:";
		[self addSubview:usernameLabel];
		
		// The username field
		boxFrame.origin.y = boxFrame.origin.y + 25.0;
		boxFrame.size.height = 28.0;
		usernameField = [ [UITextField alloc] initWithFrame:boxFrame];
		usernameField.borderStyle = UITextBorderStyleRoundedRect;
		usernameField.autocorrectionType = UITextAutocorrectionTypeNo;
		usernameField.autocapitalizationType = UITextAutocapitalizationTypeNone;
		usernameField.returnKeyType = UIReturnKeyDone;
		usernameField.delegate = self;
		usernameField.placeholder = @"YouArchive.It username";
		usernameField.clearButtonMode = UITextFieldViewModeWhileEditing;
		NSString *username = [data getData:@"username"];
		if(![username isEqualToString:@""])
		{
			usernameField.text = username;
		}
		else
		{
			disableSwitch = YES;
		}
		[self addSubview:usernameField];
		
		// Label for password field
		boxFrame.origin.y = boxFrame.origin.y + 45.0;
		boxFrame.size.height = 22.0;
		passwordLabel = [ [UILabel alloc] initWithFrame:boxFrame];
		passwordLabel.text = @"Password:";
		[self addSubview:passwordLabel];
		
		// The password field
		boxFrame.origin.y = boxFrame.origin.y + 25.0;
		boxFrame.size.height = 28.0;
		passwordField = [ [UITextField alloc] initWithFrame:boxFrame];
		passwordField.borderStyle = UITextBorderStyleRoundedRect;
		passwordField.clearsOnBeginEditing = YES;
		passwordField.secureTextEntry = YES;
		passwordField.autocorrectionType = UITextAutocorrectionTypeNo;
		passwordField.autocapitalizationType = UITextAutocapitalizationTypeNone;
		passwordField.returnKeyType = UIReturnKeyDone;
		passwordField.delegate = self;
		passwordField.placeholder = @"YouArchive.It password";
		NSString *password = [data getData:@"password"];
		if(![password isEqualToString:@""])
		{
			passwordField.text = password;
		}
		else
		{
			disableSwitch = YES;
		}
		[self addSubview:passwordField];
		
		// The privacy switch label
		boxFrame.origin.y = boxFrame.origin.y + 55.0;
		boxFrame.size.height = 22.0;
		privacyLabel = [ [UILabel alloc] initWithFrame:boxFrame];
		privacyLabel.text = @"Enable Privacy Mode:";
		[self addSubview:privacyLabel];
		
		// The privacy mode switch
		boxFrame.size.height = boxFrame.size.width = 10.0; // UISwitch ignore size values
		boxFrame.origin.x = boxFrame.origin.x + 180.0;
		privacySwitch = [ [UISwitch alloc] initWithFrame:boxFrame];
		[privacySwitch addTarget:self action:@selector(switchChanged) forControlEvents:UIControlEventValueChanged];
		NSNumber *privacyNumber = [data getData:@"privacymode"];
		BOOL privacyValue;
		if(privacyNumber == nil)
		{
			privacyValue = NO;
		}
		else
		{
			privacyValue = [privacyNumber boolValue];
		}
		privacySwitch.on = privacyValue;
		if(disableSwitch)
		{
			privacySwitch.enabled = NO;
		}
		[self addSubview:privacySwitch];
		
		// The donate text and button
		boxFrame.origin.y = boxFrame.origin.y + 40.0;
		boxFrame.size.height = 120.0;
		boxFrame.origin.x = 5.0;
		boxFrame.size.width= 310.0;
		donateText = [ [UITextView alloc] initWithFrame:boxFrame];
		donateText.text = @"If you like this app, please consider donating. Your support allows us to improve the service every day.\nAlso, users who donate 5€ or more will see their message storing limit removed.";
		donateText.editable = NO;
		donateText.userInteractionEnabled = NO;
		donateText.font = [UIFont fontWithName:@"Helvetica" size:15.0];
		donateText.textAlignment = UITextAlignmentCenter;
		[self addSubview:donateText];
		
		donateButton = [UIButton buttonWithType:UIButtonTypeCustom];
		[donateButton setImage:[UIImage imageNamed:@"Paypal.gif"] forState:UIControlStateNormal];
		donateButton.frame = CGRectMake(129.0, boxFrame.origin.y + 110, 62.0, 31.0);
		[donateButton addTarget:self action:@selector(donateButtonClicked) forControlEvents:UIControlEventTouchUpInside];
		[self addSubview:donateButton];
		
		// The "About" page
		aboutView = [ [UIWebView alloc] initWithFrame:frame];
		aboutView.delegate = self;
		NSURLRequest *aRequest=[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"AboutText" ofType:@"html"]] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
		[aboutView loadRequest:aRequest];
	}
	return self;
}

-(void)donateButtonClicked
{
	NSString *URLString = [NSString stringWithFormat:@"%@%@", @BASEURL, @"donate.php"];
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:URLString]];
}

-(void)switchChanged
{	
	TextAlertView *alert = [[TextAlertView alloc] initWithTitle:@"Password" message:@"Please insert your password to confirm." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
	alert.textField.secureTextEntry = YES;
	alert.textField.autocorrectionType = UITextAutocorrectionTypeNo;
	alert.textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
	[alert show];
	[alert autorelease];
}

- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	TextAlertView *alertView = (TextAlertView*) actionSheet;
	
	if(buttonIndex > 0 && [[data getData:@"password"] isEqualToString:alertView.textField.text])
	{
		[data setValue:[NSNumber numberWithBool:privacySwitch.on] forData:@"privacymode"];
		
		NSString *message = nil;
		if(privacySwitch.on)
		{
			message = @"Privacy Mode enabled";
		}
		else
		{
			message = @"Privacy Mode disabled";
		}
		
		UIAlertView *alertMessage = [ [UIAlertView alloc] initWithTitle:message message:@"In order to activate the changes you'll need to restart iTextUploader" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alertMessage show];
		[alertMessage autorelease];
	}
	else
	{
		BOOL newVal = !privacySwitch.on;
		[data setValue:[NSNumber numberWithBool:newVal] forData:@"privacymode"];
		privacySwitch.on = newVal;
		UIAlertView *alertMessage = [ [UIAlertView alloc] initWithTitle:@"Incorrect password" message:@"The password you inserted is not correct." delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
		[alertMessage show];
		[alertMessage autorelease];
	}
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
	[aboutView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById(\"title\").innerHTML = 'iTextUploader %@'", @APPVERSION]];
}

-(void)isGoingToVisible
{
	mainView.navItem.title = @"Preferences";
	UIBarButtonItem *aboutButton = [[UIBarButtonItem alloc] initWithTitle:@"About" style:UIBarButtonItemStylePlain target:self action:@selector(showAbout)];
	[aboutButton autorelease];
	[mainView.navItem setRightBarButtonItem:aboutButton animated:NO];
	[aboutView removeFromSuperview];
}

-(void)isGoingToHidden
{
	[mainView.navItem setRightBarButtonItem:nil animated:NO];
}

-(void)showAbout
{
	[self addSubview:aboutView];
	mainView.navItem.title = @"About";
	
	UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleDone target:self action:@selector(hideAbout)];
	[backButton autorelease];
	[mainView.navItem setRightBarButtonItem:backButton animated:NO];
}

-(void)hideAbout
{
	[aboutView removeFromSuperview];
	[self isGoingToVisible];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	if(![passwordField.text isEqualToString:[data getData:@"password"]])
	{
		privacySwitch.on = NO;
	}
	
	if(usernameField.text != nil)
	{
		[data setValue:usernameField.text forData:@"username"];
	}
	
	if(passwordField.text != nil)
	{
		[data setValue:passwordField.text forData:@"password"];
	}
	
	[textField resignFirstResponder];
	
	if(![[data getData:@"username"] isEqualToString:@""] && ![[data getData:@"password"] isEqualToString:@""])
	{
		[home loadHome];
		privacySwitch.enabled = YES;
	}
	else
	{
		privacySwitch.enabled = NO;
	}
	
	return NO;
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
	NSURL *theURL = [request URL];
	NSURL *ourURL = [NSURL URLWithString:@BASEURL];
	
	if([@"file" isEqualToString:[theURL scheme]] || [@"about" isEqualToString:[theURL scheme]] ||
	   [[ourURL host] isEqualToString:[theURL host]])
	{
		return YES;
	}
	
	[[UIApplication sharedApplication] openURL:theURL];
	return NO;
}

- (void)dealloc
{
	[usernameLabel release];
	[usernameField release];
	
	[passwordLabel release];
	[passwordField release];
	
	[privacyLabel release];
	[privacySwitch release];
	
	[donateText release];
	
	[aboutView release];
	
	[data release];
	[home release];
	[mainView release];
	
	[super dealloc];
}


@end
